﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using FastFood.Business.Entities;
using FastFood.DataAccess;

namespace FastFood.Business.Logic
{
    public class MenuCn
    {
        public List<Menus> ObtenerMenusPorContenedor(byte? id)
        {
            return MenuDalc.Instancia.ObtenerMenusPorContenedor(id);
        }

        public Menus ObtenerMenuPorID(byte id)
        {
            return MenuDalc.Instancia.ObtenerMenuPorID(id);
        }

        public List<Menus> ObtenerMenusRaicesPorUsuario(short id)
        {
            List<Formularios> formularios = FormularioDalc.Instancia.ObtenerFormulariosPorUsuarioID(id);
            List<Menus> buffer=new List<Menus>();
            Menus menu, menuP;
            bool continua=false;

            foreach (Formularios formulario in formularios)
            {
                if ((menu = getMenuFromBuffer(buffer, formulario.menuID)) != null)
                {
                    menu.Formularios.Add(formulario);
                    formulario.Menu = menu;
                }
                else
                {
                    menu = MenuDalc.Instancia.ObtenerMenuPorID(formulario.menuID);
                    menu.Formularios.Add(formulario);
                    formulario.Menu = menu;
                    buffer.Add(menu);
                    if (menu.contenedorID != null) continua = true;
                    else continua = false;

                    while (continua)
                    {
                        if ((menuP = getMenuFromBuffer(buffer, menu.contenedorID.Value)) != null) continua = false;
                        else
                        {
                            menuP = MenuDalc.Instancia.ObtenerMenuPorID(menu.contenedorID.Value);
                            buffer.Add(menuP);
                            if (menuP.contenedorID != null) continua = true;
                            else continua = false;
                        }
                        menuP.MenusHijos.Add(menu);
                        menu.MenuPadre = menuP;
                        menu = menuP;
                    }
                }
            }
            return getMenusRaices(buffer);
        }

        private Menus getMenuFromBuffer(List<Menus> buffer, short MenuId)
        {
            foreach(Menus menu in buffer)
            {
	            if(menu.menuID==MenuId) return menu; 
            }
            return null;
        }

        private List<Menus> getMenusRaices(List<Menus> buffer)
        {
            List<Menus> menus = new List<Menus>();
            foreach(Menus menu in buffer)
            {
	            if(menu.MenuPadre==null) menus.Add(menu); 
            }
            return menus;
        }
    }
}
